package org.zoomdev.zoom.lockfree;

import jdk.internal.util.ArraysSupport;
import sun.misc.Unsafe;

import java.lang.annotation.Native;
import java.util.Arrays;

public class TestStringBuilder {

    private byte[] value = new byte[1024];

    private int count;
    @Native
    static final byte LATIN1 = 0;
    @Native static final byte UTF16  = 1;
    public void reset(){
        count = 0;
    }
    private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        int oldCapacity = value.length >> LATIN1;
        if (minimumCapacity - oldCapacity > 0) {
            value = Arrays.copyOf(value,newCapacity(minimumCapacity) << LATIN1);
        }
    }
    public static final int SOFT_MAX_ARRAY_LENGTH = Integer.MAX_VALUE - 8;
    public static int newLength(int oldLength, int minGrowth, int prefGrowth) {
        // preconditions not checked because of inlining
        // assert oldLength >= 0
        // assert minGrowth > 0

        int prefLength = oldLength + Math.max(minGrowth, prefGrowth); // might overflow
        if (0 < prefLength && prefLength <= SOFT_MAX_ARRAY_LENGTH) {
            return prefLength;
        } else {
            // put code cold in a separate method
            return hugeLength(oldLength, minGrowth);
        }
    }
    private static int hugeLength(int oldLength, int minGrowth) {
        int minLength = oldLength + minGrowth;
        if (minLength < 0) { // overflow
            throw new OutOfMemoryError(
                    "Required array length " + oldLength + " + " + minGrowth + " is too large");
        } else if (minLength <= SOFT_MAX_ARRAY_LENGTH) {
            return SOFT_MAX_ARRAY_LENGTH;
        } else {
            return minLength;
        }
    }
    private int newCapacity(int minCapacity) {
        int oldLength = value.length;
        int newLength = minCapacity << LATIN1;
        int growth = newLength - oldLength;
        int length = newLength(oldLength, growth, oldLength + (2 << LATIN1));
        if (length == Integer.MAX_VALUE) {
            throw new OutOfMemoryError("Required length exceeds implementation limit");
        }
        return length >> LATIN1;
    }
    public void append(String str){
        int len = str.length();
        ensureCapacityInternal(count + len);
        putStringAt(count, str);
        count += len;
    }
    Unsafe unsafe = Unsafe.getUnsafe();

    private void putStringAt(int index, String str) {
        //str.getBytes(value, index, LATIN1);
        //unsafe.objectFieldOffset();

        //unsafe.
                //System.arraycopy(str.value, 0, dst, dstBegin << coder, value.length);
        //System.arraycopy(value, 0, value, count, value.length);
    }
}
